import * as actionTypes from './actionTypes'

// immutable 解决修改 state 的问题，他不改 state，set 方法会结合之前 immutable 对象的值和新值，并返回一个全新对象
import {
  fromJS
} from 'immutable'

// 把 js 对象 转化为 immutable 对象
const defaultState = fromJS({
  topicList: [],
  articleList: [],
  recommendList: [],
  articlePage: 1,
  showScroll: false
})

const changeHomeData = (state, action) => {
  return state.merge({
    topicList: fromJS(action.data.topicList), // 转化为 immutable 数组
    articleList: fromJS(action.data.articleList), // 转化为 immutable 数组
    recommendList: fromJS(action.data.recommendList), // 转化为 immutable 数组
  })
}

const addArticleList = (state, action) => {
  return state.merge({
    'articleList': state.get('articleList').concat(fromJS(action.list)),
    'articlePage': action.nextPage
  });
}

export default (state = defaultState, action) => {

  switch (action.type) {

    case actionTypes.CHANGE_HOME_DATA:
      return changeHomeData(state, action)

    case actionTypes.ADD_ARTICLE_LIST:
      return addArticleList(state, action)

    case actionTypes.TOGGLE_SCROLL_TOP:
      return state.set('showScroll', action.show);

    default:
      return state
  }
}